import React, {useEffect, useState} from "react";
import {Button, Form, Input, message, Modal, Popconfirm, Skeleton, Table} from 'antd';
import {fetch, MethodEnum} from "f22"
import {EditableCell} from "./editCell";

export interface SubjectPo {
  id: number,
  subjectName: string,
  pid: number,
  createTime: string,
  updateTime: string,
  level?: number
}

export function diSubjects(items, i = 1) {
  return items.map(item => {
    let {children = [], ...reset} = item
    reset.label = reset.subjectName
    reset.value = reset.id
    reset.level = i
    if (!children.length) return reset
    return {...reset, children: diSubjects(children, i + 1)}
  })
}

export default function TreeData() {
  const [form] = Form.useForm();
  const [data, setData] = useState<SubjectPo[] | null>(null);
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.id.toString() === editingKey;
  const [refreshTag, setRefreshTag] = useState(0);
  const [addPid, setAddPid] = useState(-1);
  const [addValue, setAddValue] = useState("");

  const columns = [
    {
      title: '学科名称',
      dataIndex: 'subjectName',
      editable: true,
    },
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '层级',
      dataIndex: 'level',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'createTime',
      render: (text, r, index) => {
        const editable = isEditing(r);
        return <>
          {
            !editable ? <Button type="link" onClick={() => edit(r)}>编辑</Button> :
              <>
                <Popconfirm title="确定要保存吗?" onConfirm={() => editSave(r)}>
                  <Button type="link">保存</Button>
                </Popconfirm>
                <Button type="link" onClick={() => cancel()}>取消</Button>
              </>
          }
          {
            !editable && r.level < 3 ? <Button type="link" onClick={() => setAddPid(() => r.id)}>新增子级</Button> : null
          }
          {
            !editable && (r.level === 3 || !r.children || r.children.length === 0) ?
              <Popconfirm title="确定要删除吗?" onConfirm={() => remove(r)}>
                <Button type="link">删除</Button>
              </Popconfirm>
              : null
          }
        </>
      }
    },
  ];

// 编辑模式
  const edit = (record) => {
    form.setFieldsValue({subjectName: record.subjectName, id: record.id});
    setEditingKey(record.id + "");
  };
  // 取消编辑
  const cancel = () => {
    setEditingKey('');
  };
  // 编辑
  const editSave = async (r: SubjectPo) => {
    const row = (await form.validateFields()) as SubjectPo;
    await fetch({
      url: "/admin/subject/edit",
      method: MethodEnum.POST,
      request: {
        id: r.id,
        subjectName: row.subjectName
      }
    })
    message.success("编辑成功")
    setEditingKey('');
    setRefreshTag(tag => tag + 1)

  }

  // 删除
  const remove = async (r: SubjectPo) => {
    await fetch({
      url: "/admin/subject/remove/" + r.id,
      method: MethodEnum.POST,
    })
    message.success("删除成功")
    setEditingKey('');
    setRefreshTag(tag => tag + 1)
  }

  // 新增
  const add = async () => {
    if (!addValue) return message.error("请输入学科名称")
    await fetch({
      url: "/admin/subject/add",
      method: MethodEnum.POST,
      request: {
        subjectName: addValue,
        pid: addPid
      }
    })
    message.success("新增成功")
    setRefreshTag(tag => tag + 1)
    setAddValue("")
    setAddPid(-1)
  }

  useEffect(() => {
    fetch<SubjectPo[]>({
      method: MethodEnum.GET,
      url: "/subject/all"
    }).then(data => {
      console.log(diSubjects(data.response));
      setData(diSubjects(data.response))
    })
  }, [refreshTag])
  if (!data) return <Skeleton/>

  // 合并列属性
  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: SubjectPo) => ({
        record,
        inputType: "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });


  return (
    <>
      <div style={{textAlign: "right"}}>
        <Button type={"primary"} onClick={(e) => {
          setAddPid(0)
        }}>新增顶级学科</Button>
      </div>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowKey={(r) => r.id}
          columns={mergedColumns}
          dataSource={data}
        />
      </Form>
      <Modal
        title="新增学科"
        visible={addPid > -1}
        onOk={() => add()}
        onCancel={() => setAddPid(a => -1)}
      >
        <Input placeholder="请输入学科名称" value={addValue} onChange={(e) => setAddValue(e.target.value)}/>
      </Modal>
    </>
  );
}


